package axonactive.vision.training.dto;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import ch.ivyteam.ivy.environment.Ivy;

public class QuestionDatatableDTO extends LazyDataModel<QuestionDTO> {
	private static final long serialVersionUID = 8948623492651618441L;
	private QuestionDTO seletedQuestion;
	private List<QuestionDTO> listQuesDTO;
	private int currentPage;
	
	public QuestionDatatableDTO() {
		super();
		this.listQuesDTO = new ArrayList<QuestionDTO>();
	}
	
	public QuestionDatatableDTO(List<QuestionDTO> listQuesDTO) {
		super();
		this.listQuesDTO = listQuesDTO;
	}
	
	public void reIndexListQuesDTO(){
		for (int i = 0; i<listQuesDTO.size(); i++) {
			if (i>seletedQuestion.getIndex()){
				listQuesDTO.get(i).setIndex(listQuesDTO.get(i).getIndex()-1);
			}
		}
	}
	
	@Override
	public QuestionDTO getRowData(String rowKey) {
		List<QuestionDTO> filters = this.listQuesDTO;
		for (QuestionDTO filter : filters) {
			if (String.valueOf(filter.getQuestion().getId()).equalsIgnoreCase(
					rowKey))
				;
			return filter;
		}
		return null;
	}

	@Override
	public Object getRowKey(QuestionDTO indivRateHeader) {
		return String.valueOf(indivRateHeader.getQuestion().getId());
	}
	
	@Override
	public List<QuestionDTO> load(int first, int pageSize,
			String sortField, SortOrder sortOrder, Map<String, String> filters) {
		List<QuestionDTO> data = new ArrayList<QuestionDTO>();

		// filter
		for (QuestionDTO emp : this.listQuesDTO) {
			boolean match = true;

			for (Iterator<String> it = filters.keySet().iterator(); it
					.hasNext();) {
				try {

					String filterProperty = it.next();
					String filterValue = filters.get(filterProperty);
					Field field = emp.getClass().getDeclaredField(
							filterProperty);
					if (!field.isAccessible()) {
						field.setAccessible(true);
					}
					String fieldValue = String.valueOf(field.get(emp));

					if (filterValue == null
							|| filterValue.equalsIgnoreCase("0")
							|| filterValue.isEmpty()
							|| fieldValue.toLowerCase().contains(
									filterValue.toLowerCase())) {
						match = true;
					} else {
						match = false;
						break;
					}
				} catch (Exception e) {
					Ivy.log().error(
							"ExaminationDatatableDTO#load: " + e.toString());
					match = false;
				}
			}

			if (match) {
				data.add(emp);
			}
		}

		// sort
		if (sortField != null) {
			Collections.sort(data, new QuestionDTOHeaderSorter(sortField,
					sortOrder));
		}

		// rowCount
		int dataSize = data.size();
		this.setRowCount(dataSize);
		Ivy.log().info("datasize: "+dataSize);
		// paginate
		if (dataSize > pageSize) {
			try {
				return data.subList(first, first + pageSize);
			} catch (IndexOutOfBoundsException e) {
				return data.subList(first, first + (dataSize % pageSize));
			}
		} else {
			return data;
		}
	}
	
	public QuestionDTO getSeletedQuestion() {
		return seletedQuestion;
	}

	public void setSeletedQuestion(QuestionDTO seletedQuestion) {
		this.seletedQuestion = seletedQuestion;
	}

	public List<QuestionDTO> getListQues() {
		return listQuesDTO;
	}

	public void setListQues(List<QuestionDTO> listQuesDTO) {
		this.listQuesDTO = listQuesDTO;
	}

	public int getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}
}

class QuestionDTOHeaderSorter implements Comparator<QuestionDTO> {
	private String sortField;
	private SortOrder sortOrder;
	private final String CONTENT = "question";
	private final String INDEX = "index";

	/**
	 * initializing sorting field and sorting order
	 * 
	 * @param sortField
	 * @param sortOrder
	 */
	public QuestionDTOHeaderSorter(String sortField, SortOrder sortOrder) {
		this.sortField = sortField;
		this.sortOrder = sortOrder;
	}

	@Override
	public int compare(QuestionDTO arg0, QuestionDTO arg1) {
		if (SortOrder.ASCENDING.toString().equals(sortOrder.toString())) {
			if (CONTENT.equalsIgnoreCase(sortField)) {
				return arg0.getQuestion()
						.getQuestion()
						.toLowerCase()
						.compareToIgnoreCase(
								arg1.getQuestion().getQuestion().toLowerCase());
			} else if (INDEX.equalsIgnoreCase(sortField)) {
				return arg0.getIndex() >= arg1.getIndex() ? 1: -1;
			}
		} else {
			if (CONTENT.equalsIgnoreCase(sortField)) {
				return arg1.getQuestion()
						.getQuestion()
						.toLowerCase()
						.compareToIgnoreCase(
								arg0.getQuestion().getQuestion().toLowerCase());
			} else if (INDEX.equalsIgnoreCase(sortField)) {
				return arg1.getIndex() >= arg0.getIndex() ? 1: -1;
			}
		}
		return 0;
	}
}

